'''
福运安康重疾保险产品计划
'''
import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper

class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "福运安康重疾保险产品计划"

    # 生成产品数据信息
    def genProductInfo(self):
        plan = {
            # 年龄段
            "year": [str(i) for i in range(18, 56)],
            # 性别
            "gender": ["M", "F"],
            # 保额
            "money": [str(i) + "0000" for i in range(10, 55, 10)],
            # 缴费方式 2 为月缴 5 年缴
            "payType": ["2", "5"],
            # 保险期限
            "expire": ["80岁"]

        }
        for v in product(plan["year"], plan["gender"], plan["money"], plan["payType"], plan["expire"]):
            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(
                v[0], v[1], v[2], v[3], v[4]
            ))
            self.mysql._conn.commit()
            print(domain[self.name]["insert_sql"].format(
                v[0], v[1], v[2], v[3], v[4]
            ))

    # 执行爬虫
    def requestJson(self, dt=None):

        data = {"reflowId": "S0MAo5AVBKoHQCrc", "createFlow": "true", "policyExtendDTO": {"businessLine": "ob"},
                "pid": "8000003166", "appPlanDTO": [{"payPeriod": "10", "period": "80", "sumIns": dt["money"]}],
                "lifeDatas": {"createdBy": "bbc2", "mediaSource": "mobi03-pakj-s248-bxpd-sxflbg04-20190601",
                              "aqtk": ""}, "insurantDTO": [
                {"sex": dt["gender"], "birth": "{year}-01-16".format(year=str(2019 - int(dt["year"])))}],
                "policyDTO": {"paymentType": dt["payType"]}, "insurerDTO": {"mobile": "18340909346"}}


        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=json.dumps(data))

        if r.status_code == 200 :

            price = Helper.decimalParse( r.json()["conPayPremium"] )
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )
        else:

            # 任务执行失败
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.updateTask(data)

            print("/*产品价格更新失败:%d*/"%dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)

